package com.example.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.example.demo.entity.Student;
import com.example.demo.listener.StudentReadListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author GuoMingXi @Email guomingxi2018@163.com
 * @Create 2022/5/31 12:01
 * @Version V1.0
 */
@RestController
public class WebUploadAndDownload {
        @Autowired
        private StudentReadListener studentReadListener;
   @PostMapping("upload")
    public String upload(MultipartFile file) throws Exception{
       ExcelReaderBuilder workBook = EasyExcel.read(file.getInputStream(), Student.class, studentReadListener);
       workBook.sheet().doRead();;
       return "success";

   }


   @GetMapping("download")
    public void download(HttpServletResponse response) throws Exception {
       Student student = new Student();
       response.setContentType("application/vnd.ms-excel");
//       String filename = URLEncoder.encode("测试","utf-8");//中文会出现乱码
       String filename="测试";
       response.setHeader("content-Disposition","attachment;filename="+filename+".xlsx");
       ExcelWriterBuilder workBook = EasyExcel.write(response.getOutputStream(), Student.class);
       ExcelWriterSheetBuilder sheet= workBook.sheet("模板");
       sheet.doWrite(initData());

   }
    private static List<Student> initData() {
        ArrayList<Student> students = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Student data = new Student();
            data.setName("杭州黑马学号0" + i);
            data.setBirthday(new Date());
            data.setGender("男");
            students.add(data);
        }
        return students;
    }


}
